<!-- Json数据预览的弹窗 -->
<template>
    <a-modal v-model:open="storage.jsonViewOpen" width="800px" centered :maskClosable="false" title="查看数据"
        @cancel="handleCancel" wrap-class-name="custom-modal-wrap">

        <div class="editor-wrap">
            <!-- <monaco-editor v-model="generateData" :readOnly="true" valueFormat="json" :minimap="true" language="json"></monaco-editor> -->
            <monaco-editor v-model="data.sourceCode" :readOnly="true" valueFormat="json" :minimap="true"
                language="json"></monaco-editor>
        </div>

        <template #footer>
            <a-button @click="handleCopyJson">复制</a-button>
            <a-button type="primary" @click="handleExportJson" v-if="globalOptions.export">导出</a-button>
        </template>

    </a-modal>
</template>

<script setup>
import { ref, reactive, watch, defineExpose } from 'vue'
import monacoEditor from '../../common/extens/monacoEditor/monacoEditor.vue'
import { message } from 'ant-design-vue'
import { generateData, fixGenerateData, globalOptions, storage } from '../../pageManager.js'

const data = reactive({
    activeKey: ['1'],
    monacoEditor: null, // 语言编辑器
    sourceCode: "",
})

/**
 * @method
 * @desc 显示
 */
const show = (value) => {
    storage.jsonViewOpen = true
}


// 监听数据的变化
watch(() => storage.jsonViewOpen, (newValue, oldValue) => {
    if (newValue) {
        data.sourceCode = fixGenerateData(JSON.parse(JSON.stringify(generateData.data)))
    }
})

// 暴露函数
defineExpose({
    show
})

/**
 * @method
 * @desc 导出json数据
 */
const handleExportJson = () => {
    let filename = "页面数据"
    let jsonString = JSON.stringify(generateData, null, 2)
    let blob = new Blob([jsonString], { type: 'application/json' })
    let url = URL.createObjectURL(blob)
    let a = document.createElement('a')
    a.href = url
    a.download = filename
    a.click()
    URL.revokeObjectURL(url)
}


/**
 * @method
 * @desc 复制json数据
 */
const handleCopyJson = () => {
    let jsonString = JSON.stringify(generateData, null, 2)
    const textArea = document.createElement("textarea")
    textArea.value = jsonString
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand("copy")
    document.body.removeChild(textArea)
    message.success("JSON数据已复制到剪贴板，直接粘贴即可")
}

/**
 * @method
 * @desc 关闭弹窗时的回调
 */
const handleCancel = () => {
    storage.jsonViewOpen = false
    // toRaw(data.monacoEditor).dispose();
}
</script>

<style lang="less" scoped>
.editor-wrap {
    background-color: #f5f5f5;
    height: 65vh;
}

:deep(.ant-tabs-nav) {
    margin: 0;
    padding-left: 20px;
}
</style>